<?php
namespace Siter\Controller;

class ZoneController extends Controller {

    public function index() {
        $m    = D2();
        $page = $m->where($this->indexExpr)->order($this->sortExpr)->page2();
        $this->assign('page', $page);
		$this->display();
    }

    public function add() {
        $id = I('get.ad_id', 0, 'intval');

        if (empty($id)) {
            throw new \Exception('参数不完整');
        }

        $m = M('vAd');

        if(!$rAd = $m->getById($id)) {
            throw new \Exception('没有找到广告');
        }

        $this->assign('record', $rAd)->display();
    }

    public function modify() {
        $id = empty($_GET['id']) ? 0 : (int)$_GET['id'];

        if(empty($id)) {
            exit('参数不完整，无法获取数据');
        }

        $m = D2();

        if(!$record = $m->where(['id' => $id])->find()) {
            exit('没有找到广告位信息');
        }

        if ($opts = $m->parseOpts($record)) {
            $record = array_merge($record, $opts);
            unset($record['opts']);
        }
	

        $this->assign('record', $record)
             ->display($tpl);
    }

    /**
     * doAdd
     * 保存增加的广告位
     *
     * @return void
     */
    public function doAdd() {
        $adId = I('post.ad_id', 0, 'intval');
		
        if(empty($adId)) {
            throw new \Exception('请指定广告编号');
        }

        if(!$adRecord = M('vAd')->where(['id' => $adId])->find()) {
            throw new \Exception('没有找到广告数据');
        }

        $uid = C('RUN_LOGIN_USER.id');

        if(empty($uid)) {
            throw new \Exception('参数不完整');
        }

        $m   = D2();
        $dao = [
            'name'      => I('post.name', ''),
            'uid'       => $uid,
            'plan_type' => $adRecord['plan_type'],
            'type'      => $adRecord['type'],
            'width'     => $adRecord['width'],
            'height'    => $adRecord['height'],
            'ad_id'     => $adId,
            'plan_id'   => $adRecord['plan_id'],
        ];

        try {
            $r = ($id = $m->save2($dao)) 
                 ? ['s' => true,  'm' => '保存成功']
                 : ['s' => false, 'm' => '保存出错'];
        } catch (\Exception $e) {
            $r = ['s' => false, 'm' => $e->getMessage()];
        }

        if (!$r['s']) {
            throw new \Exception($r['m']);
        }

        header('location:?c=Zone&a=getCode&id=' . $id);
    }

    public function doSave() {
        $d = $_POST;
        $m = D2();

        try {
            $r = $m->save2($d) ? array('s' => true, 'm' => '保存成功') : array('s' => false, 'm' => '保存出错');
        } catch (Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        echo json_encode($r);
    }

    /**
     * getCode
     * 获取广告位代码页面
     *
     * @return void
     */
    public function getCode() {
        $id = I('get.id', 0, 'intval');

        if(empty($id)) {
            throw new \Exception('参数不完整');
        }

        $m = D('Zone');

        /**
         * 数据库同步有出现延迟，所以此处可能会出现短时间找不到广告位的情况
         * 此页面是从添加广告位时直接跳转过来的，所以从前一页面到达此页面时时间很短，可能数据库还没同步过来
         */
        if (!$record = $m->where(['id' => $id])->find()) {
            throw new \Exception("未找到广告位数据");
        }

        $this->assign('record', $record)->display();
    }

    public function del() {
        $id = empty($_GET['id']) ? 0 : (int)$_GET['id'];

        if(empty($id)) {
            showJson(array('s' => false, 'm' => '参数不完整，无法删除数据'));
        }

        try {
            $m = D2();
            $r = $m->del($id) ? array('s' => true, 'm' => '删除成功') : array('s' => false, 'm' => '删除出错');
        } catch(Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * preview
     * 智能广告位预览
     *
     * @return void
     */
    public function preview() {
        $type   = empty($_GET['zone_type'])   ? '' : $_GET['zone_type'];
        $width  = empty($_GET['zone_width'])  ? 0  : (int)$_GET['zone_width'];
        $height = empty($_GET['zone_height']) ? 0  : (int)$_GET['zone_height'];

        if(empty($type) || empty($width) || empty($height)) {
            exit('参数不完整');
        }

        $m = D2('Zone');

        try {
            if(!$adInfo = $m->getZnAdInfo($type, $width, $height)) {
                throw new Exception('没有匹配到合适的广告素材');
            }

            if(!$tmp = D2('Ad')->getAdsByTypeAndSize($type, $adInfo['width'], $adInfo['height'])) {
                throw new Exception('没有找到合适的广告');
            }

            $tmpAdRecord = array();

            foreach($tmp as $v) {
                foreach($v['ads'] as $v2) {
                    if($v2['status'] == 1) {    //只接受处于投放状态的ytyf
                        $tmpAdRecord[] = $v2;
                    }
                }
            }

            $total    = $adInfo['col'] * $adInfo['row'];
            $adRecord = array();

            for($i = 0; $i < $total; $i++) {
                $adRecord[] = $tmpAdRecord[array_rand($tmpAdRecord)];
            }
        } catch(Exception $e) {
            exit($e->getMessage());
        }

        $zoneWidth  = $width;
        $zoneHeight = $height;

        include($adInfo['list_tpl']);
    }

    /**
     * previewColorCloud
     * 彩色文字云预览
     *
     * @return void
     */
    public function previewColorCloud() {
        $type   = 'zn_color_cloud';
        $width  = empty($_GET['zone_width'])  ? 0  : (int)$_GET['zone_width'];
        $height = empty($_GET['zone_height']) ? 0  : (int)$_GET['zone_height'];

        if(empty($width) || empty($height)) {
            exit('参数不完整');
        }

        $m = D2('Zone');

        try {
            /**
             * 找出120x20的智能文字广告
             */
            if(!$tmp = D2('Ad')->getAdsByTypeAndSize('zn_text', 120, 20)) {
                throw new Exception('没有找到合适的广告');
            }

            $tmpAdRecord = array();

            foreach($tmp as $v) {
                foreach($v['ads'] as $v2) {
                    if($v2['status'] == 1) {    //只接受处于投放状态的广告
                        $tmpAdRecord[] = $v2;
                    }
                }
            }

            $total   = 20;
            $records = array();

            for($i = 0; $i < $total; $i++) {
                $tmpRow = $tmpAdRecord[array_rand($tmpAdRecord)];
                $htmls = explode('<!--tpl-->', str_replace('<!--/tpl-->', '<!--tpl-->', $tmpRow['code']));
                $text  = strip_tags($htmls[1]);

                $records[] = array(
                    't' => $text,
                    'g' => $tmpRow['url'],
                );
            }
        } catch(Exception $e) {
            exit($e->getMessage());
        }

        $colorStyle       = !isset($_GET['color_style']) ? 0 : (int)$_GET['color_style'];    //颜色风格
        $zoneWidth        = $width;
        $zoneHeight       = $height;
        $colorCloudjsFile = getFullUrl(C('ad_js_base_url')) . '/c.js';
        $cpcJsFile        = getFullUrl(C('ad_js_base_url')) . '/b.js';
        $items            = json_encode($records);

        include(realpath(THINK_PATH . '../Public/Tpl/ZnAd/color_cloud.php'));
    }

    /**
     * doZnZoneSave
     * 保存智能广告位
     *
     * @return void
     */
    public function doZnZoneSave() {
        $d        = $_POST;
        $m        = D2('Zone');
        $d['uid'] = C('RUN_LOGIN_USER.uid');
        $action   = strtolower($d['zone_type']) == 'zn_color_cloud' ? 'saveZnColorCloud' : 'saveZnZone';

        try {
            //saveZnZone()成功时返回广告位编号，出错时返回false
            $r = (!$_r = $m->$action($d)) ?  array('s' => false, 'm' => '保存广告位出错') : array('s' => true, 'd' => $_r);
        } catch(Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * getPlanDevicesName
     * 返回投放备名称信息
     *
     * @return void
     */
    public function getPlanDevicesName() {
        $planId = I('get.plan_id', 0, 'intval');

        if (empty($planId)) {
            showJson(array('s' => false, 'm' => '请指定计划编号'));
        }

        $planDeviceModel = D2('PlanDevice');

        if (!$records = $planDeviceModel->where(array('plan_id' => $planId))->select()) {
            showJson(array('s' => false, 'm' => '没有找到投放设备数据'));
        }

        $r = array();

        foreach ($records as $k => $v) {
            if ($v['pd_device'] == 4) {
                continue;
            }

            $r[] = getPlanDeviceNameById($v['pd_device']);
        }

        showJson(array('s' => true, 'd' => $r));
    }

}
